package com.enhe.gck.com.oracle;

import org.scribe.exceptions.OAuthParametersMissingException;
import org.scribe.model.OAuthRequest;
import org.scribe.model.ParameterList;
import org.scribe.services.Base64Encoder;
import org.scribe.utils.OAuthEncoder;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
public class HMACExampleUtils {
	public String getMima(OAuthRequest request,String consumerSecret,String accessTokenSecret) {
		if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0) {
			throw new OAuthParametersMissingException(request);
		}
		String verb = OAuthEncoder.encode(request.getVerb().name());
		String url = OAuthEncoder.encode(request.getSanitizedUrl());
		ParameterList params = new ParameterList();
		params.addAll(request.getQueryStringParams());
		params.addAll(request.getBodyParams());
		params.addAll(new ParameterList(request.getOauthParameters()));
		String baseString = String.format("%s&%s&%s", verb, url, params.sort().asOauthBaseString());
		String signingKey =OAuthEncoder.encode(consumerSecret) + '&' + OAuthEncoder.encode(accessTokenSecret);
		return calculateHMACSHA256(baseString, signingKey);
	}

	// Calculate HMAC-SHA256 signature
	private static String calculateHMACSHA256(String data, String keyString) {
		try {
			SecretKeySpec key = new SecretKeySpec(keyString.getBytes("UTF-8"), "HmacSHA256");
			Mac mac = Mac.getInstance("HmacSHA256");
			mac.init(key);
			byte[] bytes = mac.doFinal(data.getBytes("UTF-8"));
			return Base64Encoder.getInstance().encode(bytes).replace("\r\n", "").replace("+","%2B");
		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
			throw new RuntimeException(e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
